<template>
  <div class="recommend-list">
    <a-page-header
      title="推荐作品管理"
      sub-title="管理首页推荐作品，包括新增、编辑和删除等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">

        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allowClear
            style="width: 150px"
          >
            <a-select-option :value="0">禁用</a-select-option>
            <a-select-option :value="1">启用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <a-button type="primary" @click="handleAdd" v-permission="'homepage:recommended:add'">
              <template #icon><plus-outlined /></template>新增推荐
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="tableData" 
        :loading="loading" 
        :pagination="{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="handleEdit(record)" v-permission="'homepage:recommended:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-popconfirm
                title="确定要删除该推荐作品吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'homepage:recommended:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
            </template>

        </template>
    </a-table>

    <!-- 新增/编辑推荐作品弹窗 -->
    <a-modal
      :title="dialogTitle"
      :visible="dialogVisible"
      @ok="submitForm"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
      width="700px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="作品ID" name="artworkId">
          <a-input-group compact>
            <a-input-number v-model:value="form.artworkId" :min="1" style="width: calc(100% - 100px)" placeholder="请输入作品ID" disabled />
            <a-button type="primary" @click="openArtworkSelector" style="width: 100px">选择作品</a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item label="推荐理由" name="reason">
          <a-textarea v-model:value="form.reason" placeholder="请输入推荐理由" :rows="3" />
        </a-form-item>
        <a-form-item label="推荐时间" name="timeRange">
          <a-range-picker 
            v-model:value="timeRange" 
            show-time 
            format="YYYY-MM-DD HH:mm:ss" 
            :placeholder="['开始时间', '结束时间']"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="form.sort" :min="0" style="width: 100%" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="form.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 作品选择弹窗 -->
    <a-modal
      title="选择作品"
      :visible="artworkSelectorVisible"
      @cancel="handleArtworkSelectorCancel"
      :footer="null"
      width="800px"
    >
      <div class="artwork-selector">
        <div class="search-bar">
          <a-input-search
            v-model:value="artworkSearchKeyword"
            placeholder="请输入作品名称搜索"
            enter-button
            @search="searchArtworks"
            style="width: 300px; margin-bottom: 16px;"
          />
        </div>
        <a-table
          :columns="artworkColumns"
          :data-source="artworkList"
          :loading="artworkLoading"
          :pagination="{
            current: artworkPagination.current,
            pageSize: artworkPagination.pageSize,
            total: artworkPagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
          }"
          @change="handleArtworkTableChange"
          rowKey="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'cover'">
              <img v-if="record.coverImage" :src="`/api${record.coverImage}`" alt="封面" style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;" />
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getArtworkStatusColor(record.status)">
                {{ getArtworkStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-button type="primary" @click="selectArtwork(record)" :disabled="record.status !== 2">选择</a-button>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, watch } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'RecommendList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const formRef = ref(null);
    const loading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增推荐作品');
    const isEdit = ref(false);
    const modalLoading = ref(false);
    const timeRange = ref([]);
    
    // 作品选择器相关变量
    const artworkSelectorVisible = ref(false);
    const artworkList = ref([]);
    const artworkLoading = ref(false);
    const artworkSearchKeyword = ref('');
    const artworkPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    
    // 作品列表表格列定义
    const artworkColumns = [
      {
        title: '作品ID',
        dataIndex: 'id',
        key: 'id',
        width: 80,
      },
      {
        title: '封面',
        dataIndex: 'coverImage',
        key: 'cover',
        width: 80,
      },
      {
        title: '作品名称',
        dataIndex: 'title',
        key: 'title',
        ellipsis: true,
      },
      {
        title: '分类',
        dataIndex: 'categoryName',
        key: 'categoryName',
        width: 120,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right',
      },
    ];
    
    // 监听时间范围变化，更新表单中的开始时间和结束时间
    watch(timeRange, (newVal) => {
      if (newVal && newVal.length === 2) {
        form.startTime = dayjs(newVal[0]).format('YYYY-MM-DD HH:mm:ss');
        form.endTime = dayjs(newVal[1]).format('YYYY-MM-DD HH:mm:ss');
      } else {
        form.startTime = '';
        form.endTime = '';
      }
    });
    
    const searchForm = reactive({
      status: undefined,
    });
    
    const form = reactive({
      id: '',
      artworkId: undefined, // 作品ID
      reason: '', // 推荐理由
      sort: 0, // 排序
      status: 1, // 状态：0-禁用，1-启用
      startTime: '', // 推荐开始时间
      endTime: '', // 推荐结束时间
    });
    
    const rules = {
      artworkId: [
        { required: true, message: '请输入作品ID', trigger: 'blur' },
      ],
      reason: [
        { max: 500, message: '推荐理由长度不能超过500个字符', trigger: 'blur' },
      ],
      sort: [
        { required: true, message: '请输入排序', trigger: 'blur' },
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' },
      ],
    };
    
    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '作品标题',
        dataIndex: 'artworkTitle',
        key: 'artworkTitle',
        width: 100,
      },
      {
        title: '推荐理由',
        dataIndex: 'reason',
        key: 'reason',
        ellipsis: true,
      },
      {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort',
        width: 80,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
      },
      {
        title: '推荐开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 180,
      },
      {
        title: '推荐结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
        width: 180,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 180,
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right',
      },
    ];

    // 获取推荐作品列表
    const fetchData = async () => {
      loading.value = true;
      try {
        const response = await axios.get('/api/recommend/page', {
          params: {
            current: currentPage.value,
            size: pageSize.value,
            status: searchForm.status,
          },
        });
        if (response.data.code === 200) {
          tableData.value = response.data.data.records;
          total.value = response.data.data.total;
        } else {
          message.error(response.data.message || '获取推荐作品列表失败');
        }
      } catch (error) {
        console.error('获取推荐作品列表出错:', error);
        message.error('获取推荐作品列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 表格分页、排序、筛选变化时触发
    const handleTableChange = (pagination) => {
      currentPage.value = pagination.current;
      pageSize.value = pagination.pageSize;
      fetchData();
    };

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1;
      fetchData();
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.status = undefined;
      currentPage.value = 1;
      fetchData();
    };

    // 新增推荐作品
    const handleAdd = () => {
      isEdit.value = false;
      dialogTitle.value = '新增推荐作品';
      resetForm();
      dialogVisible.value = true;
    };

    // 编辑推荐作品
    const handleEdit = (record) => {
      isEdit.value = true;
      dialogTitle.value = '编辑推荐作品';
      Object.assign(form, record);
      
      // 设置时间范围
      if (record.startTime && record.endTime) {
        timeRange.value = [
          dayjs(record.startTime),
          dayjs(record.endTime)
        ];
      } else {
        timeRange.value = [];
      }
      
      dialogVisible.value = true;
    };

    // 删除推荐作品
    const handleDelete = async (id) => {
      try {
        const response = await axios.delete(`/api/recommend/${id}`);
        if (response.data.code === 200) {
          message.success('删除成功');
          fetchData();
        } else {
          message.error(response.data.message || '删除失败');
        }
      } catch (error) {
        console.error('删除推荐作品出错:', error);
        message.error('删除失败');
      }
    };

    // 重置表单
    const resetForm = () => {
      form.id = '';
      form.artworkId = undefined;
      form.reason = '';
      form.startTime = '';
      form.endTime = '';
      form.sort = 0;
      form.status = 1;
      timeRange.value = [];
    };

    // 取消弹窗
    const handleModalCancel = () => {
      dialogVisible.value = false;
      resetForm();
    };

    // 提交表单
    const submitForm = () => {
      formRef.value.validate().then(async () => {
        modalLoading.value = true;
        try {
          let response;
          if (isEdit.value) {
            response = await axios.put(`/api/recommend/${form.id}`, form);
          } else {
            response = await axios.post('/api/recommend', form);
          }
          
          if (response.data.code === 200) {
            message.success(isEdit.value ? '更新成功' : '添加成功');
            dialogVisible.value = false;
            resetForm();
            fetchData();
          } else {
            message.error(response.data.message || (isEdit.value ? '更新失败' : '添加失败'));
          }
        } catch (error) {
          console.error(isEdit.value ? '更新推荐作品出错:' : '添加推荐作品出错:', error);
          message.error(isEdit.value ? '更新失败' : '添加失败');
        } finally {
          modalLoading.value = false;
        }
      }).catch(error => {
        console.log('表单验证失败:', error);
      });
    };

    // 打开作品选择器
    const openArtworkSelector = () => {
      artworkSelectorVisible.value = true;
      artworkSearchKeyword.value = '';
      artworkPagination.current = 1;
      fetchArtworkList();
    };

    // 关闭作品选择器
    const handleArtworkSelectorCancel = () => {
      artworkSelectorVisible.value = false;
    };

    // 获取作品列表
    const fetchArtworkList = (page = artworkPagination.current, pageSize = artworkPagination.pageSize) => {
      artworkLoading.value = true;
      const params = {
        page,
        pageSize,
        title: artworkSearchKeyword.value,
        status: 2, // 默认只显示已发布的作品
      };
      
      axios.get('/api/artwork/page', { params })
        .then(response => {
          if (response.data.code === 200) {
            artworkList.value = response.data.data.records;
            artworkPagination.total = response.data.data.total;
            artworkPagination.current = page;
            artworkPagination.pageSize = pageSize;
          } else {
            message.error(response.data.message || '获取作品列表失败');
          }
        })
        .catch(error => {
          console.error('获取作品列表失败:', error);
          message.error('获取作品列表失败');
        })
        .finally(() => {
          artworkLoading.value = false;
        });
    };

    // 搜索作品
    const searchArtworks = () => {
      artworkPagination.current = 1;
      fetchArtworkList();
    };

    // 作品表格分页变化
    const handleArtworkTableChange = (pagination) => {
      fetchArtworkList(pagination.current, pagination.pageSize);
    };

    // 选择作品
    const selectArtwork = (record) => {
      form.artworkId = record.id;
      artworkSelectorVisible.value = false;
      message.success(`已选择作品：${record.title}`);
    };

    // 获取作品状态文本
    const getArtworkStatusText = (status) => {
      switch (status) {
        case 0: return '草稿';
        case 1: return '审核中';
        case 2: return '已发布';
        case 3: return '已拒绝';
        default: return '未知';
      }
    };

    // 获取作品状态颜色
    const getArtworkStatusColor = (status) => {
      switch (status) {
        case 0: return 'default';
        case 1: return 'orange';
        case 2: return 'green';
        case 3: return 'red';
        default: return 'default';
      }
    };

    onMounted(() => {
      fetchData();
    });

    return {
      formRef,
      loading,
      tableData,
      total,
      currentPage,
      pageSize,
      dialogVisible,
      dialogTitle,
      isEdit,
      modalLoading,
      timeRange,
      searchForm,
      form,
      rules,
      columns,
      handleTableChange,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      handleModalCancel,
      submitForm,
      // 作品选择器相关
      artworkSelectorVisible,
      artworkList,
      artworkLoading,
      artworkSearchKeyword,
      artworkPagination,
      artworkColumns,
      openArtworkSelector,
      handleArtworkSelectorCancel,
      searchArtworks,
      handleArtworkTableChange,
      selectArtwork,
      getArtworkStatusText,
      getArtworkStatusColor,
    };
  },
});
</script>

<style scoped>
.recommend-list {
  background-color: transparent;
}
.search-card {
  margin-bottom: 20px;
}
.artwork-selector {
  padding: 0 10px;
}
.search-bar {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 16px;
}
</style>